<template>
  <div class="container">
    <div>
      <div class="btn_container">
        <el-button class="imageDrown" type="primary" @click="visible = true">
          新增
        </el-button>
        <div class="refreshBtn" @click="getList">
          <el-icon>
            <Refresh />
          </el-icon>
        </div>
      </div>
    </div>
    <el-table
      :data="tableData"
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="id" label="ID" />
      <el-table-column prop="name" label="任务名" />
      <el-table-column prop="delivery_time" label="投放时间" />
      <el-table-column prop="duration" label="养号时长" />
      <el-table-column prop="status" label="状态" />
      <el-table-column prop="create_time" label="创建时间	" />
      <el-table-column prop="operate" label="操作" width="200" align="center">
        <template #default="scope">
          <el-dropdown @command="(e) => handleOperate(e, scope.row)">
            <el-button class="videoDrown">
              操作
              <el-icon class="el-icon--right"><arrow-down /></el-icon>
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="delete">删除养号</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>
    <div class="page_container">
      <el-pagination
        v-model:current-page="page"
        v-model:page-size="page_size"
        :page-sizes="[10, 20, 30, 40]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <el-dialog
      v-model="visible"
      title="添加养号任务"
      width="600"
      center
      @close="resetForm"
    >
      <el-form
        :inline="true"
        :model="modelForm"
        ref="modelFormRef"
        label-width="100px"
        :rules="rules"
      >
        <el-form-item label="执行时间" class="model-item" prop="delivery_time">
          <el-date-picker
            v-model="modelForm.delivery_time"
            type="datetime"
            placeholder="执行时间"
          />
        </el-form-item>
        <el-form-item label="任务名" class="model-item" prop="name">
          <el-input v-model="modelForm.name" placeholder="请输入任务名称">
          </el-input>
        </el-form-item>
        <el-form-item label="养号时长" class="model-item" prop="duration">
          <el-input
            v-model.number="modelForm.duration"
            placeholder="请输入养号时长"
          >
            <template #suffix>分钟</template>
          </el-input>
        </el-form-item>
        <el-form-item label="点赞配置" class="model-item">
          <el-col :span="11">
            <el-form-item prop="like_rate">
              <el-input v-model="modelForm.like_rate">
                <template #prefix>概率</template>
                <template #suffix>%</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="2"></el-col>
          <el-col :span="11">
            <el-form-item prop="like_limit">
              <el-input v-model.number="modelForm.like_limit">
                <template #prefix>上限</template>
                <template #suffix>条</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-form-item>
        <el-form-item label="收藏配置" class="model-item">
          <el-col :span="11">
            <el-form-item prop="collect_rate">
              <el-input v-model="modelForm.collect_rate">
                <template #prefix>概率</template>
                <template #suffix>%</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="2"></el-col>
          <el-col :span="11">
            <el-form-item prop="collect_limit">
              <el-input v-model.number="modelForm.collect_limit">
                <template #prefix>上限</template>
                <template #suffix>条</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-form-item>
        <el-form-item label="评论配置" class="model-item">
          <el-col :span="11">
            <el-form-item prop="comment_rate">
              <el-input v-model="modelForm.comment_rate">
                <template #prefix>概率</template>
                <template #suffix>%</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="2"></el-col>
          <el-col :span="11">
            <el-form-item prop="comment_limit">
              <el-input v-model.number="modelForm.comment_limit">
                <template #prefix>上限</template>
                <template #suffix>条</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-form-item>
        <el-form-item label="评论词组" prop="comments" class="model-item">
          <el-input
            v-model="modelForm.comments"
            type="textarea"
            rows="4"
            placeholder="请输入内容, 每行一个文案内容,敲击回车换行"
          />
        </el-form-item>
        <el-form-item label="关键词组" prop="keywords" class="model-item">
          <el-input
            v-model="modelForm.keywords"
            type="textarea"
            rows="4"
            placeholder="请输入内容, 每行一个文案内容,敲击回车换行"
          />
        </el-form-item>
        <el-form-item label="指定用户">
          <el-button @click="handleUser">选择</el-button>
          <el-tag
            v-for="item in user_multipleSelection"
            :key="item.id"
            closable
            @close="handleClose(item)"
            style="margin-left: 10px"
          >
            {{ item.name }}
          </el-tag>
        </el-form-item>
        <div class="modalBtns">
          <el-button @click="visible = false">取消</el-button>
          <el-button type="primary" @click="onSubmit" :loading="loading"
            >确定</el-button
          >
        </div>
      </el-form>
    </el-dialog>
    <el-dialog v-model="deleteShow" title="提示" width="400">
      确定删除此内容
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="deleteShow = false">取消</el-button>
          <el-button type="primary" @click="handDelete"> 确定 </el-button>
        </span>
      </template>
    </el-dialog>
    <el-dialog v-model="userShow" width="800" center>
      <div>
        <el-input
          v-model="userName"
          placeholder="请输入用户名称"
          style="width: 240px"
          clearable
        />
        <el-button
          type="primary"
          @click="handleUserSearch"
          style="margin-left: 21px"
          >搜索</el-button
        >
        <el-table
          :data="userList"
          style="width: 100%; margin-top: 10px"
          @selection-change="handleUserSelectionChange"
          ref="multipleTableRef"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column prop="name" label="用户名" />
          <el-table-column prop="number" label="红薯号" />
          <el-table-column
            prop="creator_status"
            label="创作者cookie状态"
            width="155"
          />
        </el-table>
        <div style="margin: 20px 0">
          <el-pagination
            v-model:current-page="user_page"
            v-model:page-size="user_page_size"
            :page-sizes="[10, 20, 30, 40]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="user_total"
            @size-change="handleUserSizeChange"
            @current-change="handleUserCurrentChange"
          />
        </div>
      </div>
      <div class="modalBtns">
        <!-- <el-button @click="userShow = false">取消</el-button> -->
        <el-button type="primary" @click="userShow = false">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script setup>
import { ref, reactive, watch } from "vue";
import {
  account_maintenance_task_list,
  account_maintenance_task_create,
  account_maintenance_task_delete,
  xhs_list,
} from "@/api/xhs.js";
import { ElMessage } from "element-plus";
import { ArrowDown, Refresh, Plus } from "@element-plus/icons-vue";
import moment from "moment";
const loading = ref(false);

const page_size = ref(10);
const page = ref(1);
const total = ref(0);
const tableData = ref([]);
const multipleSelection = ref([]);
const modelForm = reactive({
  delivery_time: new Date(),
  duration: "",
  like_rate: "",
  like_limit: "",
  collect_rate: "",
  collect_limit: "",
  comment_rate: "",
  comment_limit: "",
  comments: "",
  keywords: "",
  name: "",
});
const modelFormRef = ref(null);

const visible = ref(false);
const deleteShow = ref(false);
const selectedItem = ref({});
const userShow = ref(false);
const userList = ref([]);
const userName = ref();
const multipleTableRef = ref(null);
const user_page_size = ref(10);
const user_page = ref(1);
const user_total = ref(0);
const user_multipleSelection = ref([]);
const toggleSelection = () => {
  if (user_multipleSelection.value.length) {
    const selected = multipleTableRef.value.getSelectionRows();
    const ids = user_multipleSelection.value.map((item) => item.id);
    const otherData = selected.filter((item) => !ids.includes(item.id));
    otherData.forEach((row) => {
      multipleTableRef.value?.toggleRowSelection(row, false);
    });
    user_multipleSelection.value.forEach((row) => {
      multipleTableRef.value?.toggleRowSelection(row, true);
    });
  } else {
    multipleTableRef.value?.clearSelection();
  }
};
const handleUser = () => {
  userShow.value = true;
  toggleSelection();
};

const handleClose = (tag) => {
  const data = user_multipleSelection.value.filter(
    (item) => item.id !== tag.id
  );
  user_multipleSelection.value = data;
};

const handleUserSelectionChange = (val) => {
  user_multipleSelection.value = val;
};
// 自定义验证函数
const validateInteger = (rule, value, callback) => {
  if (value !== "" && (!Number.isInteger(value) || value <= 0)) {
    callback(new Error("养号时长必须是正整数"));
  } else {
    callback();
  }
};

const validateLimitInteger = (rule, value, callback) => {
  if (value !== "" && (!Number.isInteger(value) || value < 0)) {
    callback(new Error("养号时长必须是正整数"));
  } else {
    callback();
  }
};
const validateValue = (rule, value, callback) => {
  if (value === "") {
    callback();
  } else if (!/^\d+(\.\d+)?$/.test(value)) {
    callback(new Error("请输入有效的数字"));
  } else {
    const num = parseFloat(value);
    if (num < 0 || num > 100) {
      callback(new Error("值必须在 0 到 100 之间"));
    } else {
      callback();
    }
  }
};
const rules = reactive({
  delivery_time: [
    { required: true, message: "请选择执行时间", trigger: "blur" },
  ],
  name: [
    { required: true, max: 50, message: "请输入任务名称", trigger: "blur" },
  ],
  duration: [
    { required: true, message: "请输入养号时长", trigger: "blur" },
    { validator: validateInteger, trigger: "blur" },
  ],
  like_rate: [{ validator: validateValue, trigger: "blur" }],
  like_limit: [{ validator: validateLimitInteger, trigger: "blur" }],
  collect_rate: [{ validator: validateValue, trigger: "blur" }],
  collect_limit: [{ validator: validateLimitInteger, trigger: "blur" }],
  comment_rate: [{ validator: validateValue, trigger: "blur" }],
  comment_limit: [{ validator: validateLimitInteger, trigger: "blur" }],
});
// 重置模态框的form表单
const resetForm = () => {
  if (modelFormRef.value) {
    modelFormRef.value.resetFields();
  }
  Object.assign(modelForm, {
    delivery_time: new Date(),
    duration: "",
    like_rate: "",
    like_limit: "",
    collect_rate: "",
    collect_limit: "",
    comment_rate: "",
    comment_limit: "",
    comments: "",
    keywords: "",
    name: "",
  });
  user_multipleSelection.value = [];
};

const handleSelectionChange = (val) => {
  multipleSelection.value = val;
};
const handleOperate = (item, row) => {
  selectedItem.value = row;
  switch (item) {
    case "delete":
      deleteShow.value = true;
      break;
  }
};
const handDelete = async () => {
  try {
    const res = await account_maintenance_task_delete({
      id: selectedItem.value.id,
    });
    if (res.code === 0) {
      ElMessage.success("删除养号成功");
      await getList({ page_size: 10, page: 1 });
    } else {
      ElMessage.error(res.msg);
    }
    deleteShow.value = false;
  } catch (err) {
    console.log(err);
  }
};
const handleSizeChange = (val) => {
  page_size.value = val;
};
const handleCurrentChange = (val) => {
  page.value = val;
};
const getList = async (params) => {
  try {
    const res = await account_maintenance_task_list({
      page_size: page_size.value,
      page: page.value,
      ...params,
    });
    if (res.code === 0) {
      tableData.value = res.data.list;
      total.value = res.data.total;
    } else {
      ElMessage.error(res.msg);
    }
  } catch (err) {
    console.log(err);
  }
};

const getUserList = async (params = {}) => {
  try {
    const res = await xhs_list({
      cookie_type: 0,
      page_size: user_page_size.value,
      page: user_page.value,
      name: userName.value,
      ...params,
    });
    if (res.code === 0) {
      userList.value = res.data.list;
      user_total.value = res.data.total;
    } else {
      ElMessage.error(res.msg);
    }
  } catch (err) {
    console.log("err");
  }
};

const handleUserSearch = async () => {
  await getUserList({ page: 1 });
};

watch(
  [user_page_size, user_page],
  () => {
    getUserList();
  },
  {
    immediate: true,
  }
);
watch(
  [page_size, page],
  () => {
    getList();
  },
  {
    immediate: true,
  }
);
const onSubmit = async () => {
  modelFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        loading.value = true;
        const {
          collect_limit,
          collect_rate,
          comment_limit,
          comment_rate,
          comments,
          delivery_time,
          duration,
          keywords,
          like_limit,
          like_rate,
          name,
        } = modelForm;
        const res = await account_maintenance_task_create({
          config: {
            collect_limit,
            collect_rate,
            comment_limit,
            comment_rate,
            like_limit,
            like_rate,
            comments: comments ? comments.split("\n") : [],
            keywords: keywords ? keywords.split("\n") : [],
            designated_accounts: user_multipleSelection.value.map((item) => {
              return {
                number: item.number,
                ads_power_id: item.ads_power_id,
                xhs_user_id: item.id,
                name: item.name,
              };
            }),
          },
          delivery_time: moment(delivery_time).format("YYYY-MM-DD HH:mm:ss"),
          duration,
          name,
        });
        if (res.code === 0) {
          visible.value = false;
          getList({ page_size: 10, page: 1 });
        } else {
          ElMessage.error(res.msg);
        }
      } catch (error) {
        console.log("error", error);
      } finally {
        loading.value = false;
      }
    } else {
      console.log("表单校验失败");
    }
  });
};
</script>
<style scoped lang="scss">
.container {
  width: 100%;
  height: 100%;
  padding: 50px;
  box-sizing: border-box;
}

.page_container {
  float: right;
  margin-top: 40px;
}

:deep(.el-table__header) {
  background-color: #f5f7fa !important;
}

:deep(.el-table tr) {
  background-color: rgba(0, 0, 0, 0);
}

:deep(.el-table th.el-table__cell) {
  background-color: rgba(0, 0, 0, 0);
}

.btn_container {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 20px;

  .imageDrown {
    margin-left: 10px;
    color: #fff;
  }

  .deleteBtn {
    color: #fff;
  }

  .videoDrown {
    margin-left: 10px;
  }

  .refreshBtn {
    width: 32px;
    height: 32px;
    display: flex;
    align-items: center;
    justify-content: center;
    background: #78d0ec63;
    color: #78d0ecf2;
    border-radius: 50%;
    margin-left: 10px;
    cursor: pointer;
  }
}

.model-item {
  width: 90%;
}

.modalBtns {
  display: flex;
  justify-content: center;
  gap: 20px;
}
</style>
